package com.anli.service;

import com.anli.leguansuo.LeGuanStockDao;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMultiLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/3/9  14:07
 * 描述:
 */
@Component
public class ZkLockService {

     @Autowired
     private LeGuanStockDao leGuanStockDao;

     @Autowired(required = false)
     private CuratorFramework curatorFramework;

     public void testZkLock(String goodsId,int lockStock) throws Exception {

         //创建锁对象
         InterProcessMutex interProcessMultiLock=new InterProcessMutex(curatorFramework,"/LOCKS");
         //获取锁
         interProcessMultiLock.acquire();

         Map<String, Object> goodsStock = leGuanStockDao.getGooodsById(goodsId);
         //if条件成立的话表示库存充足
         if(Long.valueOf(goodsStock.get("stock").toString())>=lockStock) {
             Map<String, Object> parm = new HashMap<>();
             parm.put("goodsId", goodsId);
             parm.put("version", goodsStock.get("version"));
             parm.put("stock", Long.valueOf(goodsStock.get("stock").toString()) - lockStock);

             //更新库存
             int updateStock = leGuanStockDao.updateStock(parm);

             System.out.println("==========>"+updateStock);
         }

         //释放锁
         interProcessMultiLock.release();
     }

}
